package com.examsystem.util;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtUtil {

    private static final String TOKEN = "#$dg^&^y@#e%ti#%$%tg";

    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim);
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,1);
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(TOKEN));
    }
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }


    public static DecodedJWT getTokenInfo(String token){
       return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }

    public static String getErrorMsg(Exception e){
        HashMap<String, Object> hashMap = new HashMap<>(2);
        hashMap.put("msg",e.getMessage());
        hashMap.put("status",false);
        return JSON.toJSONString(hashMap);
    }

    public static int getJWTUserId(String token){
        DecodedJWT tokenInfo = JwtUtil.getTokenInfo(token);
        String userIdStr = tokenInfo.getClaim("userId").asString();
        return Integer.parseInt(userIdStr);
    }
}
